package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpResponse {
    private String protocol ="HTTP/1.1";
    private int statusCode =200;
    private String statusReason ="OK";
    private Map<String,String> headers =new HashMap<>();
    private File entity;
    private Socket socket;
    public HttpResponse(Socket socket){
        this.socket=socket;
    }
    public void flush() throws IOException {
        sendStatusLine();
        sendHeaders();
        sendContent();
    }
    private void sendStatusLine() throws IOException {
        String line =protocol+" "+statusCode+" "+statusReason;
        println(line);
    }
    private void sendHeaders() throws IOException {
        Set<Map.Entry<String,String>> entrySet=headers.entrySet();
        for (Map.Entry<String,String> e:entrySet){
            String name =e.getKey();
            String value =e.getValue();
            String line =name+": "+value;
            println(line);
        }
        println("");
    }
    private void sendContent() throws IOException {
        OutputStream out = socket.getOutputStream();
        if (entity != null) {
            try (FileInputStream fis = new FileInputStream(entity);) {
                byte[] buf = new byte[1024 * 8];
                int len;
                while ((len = fis.read(buf)) != -1) {
                    out.write(buf, 0, len);
                }
            }
        }
    }
    private void println(String line) throws IOException {
        OutputStream out =socket.getOutputStream();
        byte[] data =line.getBytes("ISO8859-1");
        out.write(data);
        out.write(13);
        out.write(10);
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    public File getEntity() {
        return entity;
    }

    public void setEntity(File entity) {
        this.entity = entity;
        String fileName=entity.getName();
        String ext =fileName.substring(fileName.lastIndexOf(".")+1);
        String type =HttpContext.getMimeType(ext);
        addHeader("Content-Type",type);
        addHeader("Content-Length",entity.length()+"");
    }
    public void addHeader(String name,String value){
        this.headers.put(name,value);
    }
}
